<template>
  <div id="OrderDetail">
    <main-header :title="'订单管理'" :crumbsArr="crumbsArr" />
    <div class="main_wrapper">
      <div
        class="main"
        v-loading="loading"
        element-loading-text="加载中"
        element-loading-background="rgba(255, 255, 255, 0.8)"
      >
        <div class="order_status">
          <span>订单状态：</span><span>{{orderStateTxt}}</span>
        </div>
        <div class="order_baseInfo order_info">
          <span>订单编号：</span><span v-if="detailData">{{detailData.orderno}}</span>
          <span>下单时间：</span><span v-if="detailData">{{detailData.createdate}}</span>
          <span>手机号：</span><span v-if="detailData">{{detailData.telephone}}</span>
          <span>客户姓名：</span><span v-if="detailData">{{detailData.nickname}}</span>
        </div>

        <div class="order_unique_info order_info"
          v-if="detailData && (orderStateTxt === '待发货' || orderStateTxt === '已发货')">
          <div class="to_send">
            <div>
              <span>收货人：</span><span>{{detailData.recipient}}</span>
            </div>
            <div>
              <span>手机号：</span><span>{{detailData.telephone}}</span>
            </div>
            <div>
              <span>收货地址：</span><span>{{detailData.address}}</span>
            </div>
          </div>
        </div>

        <div class="order_unique_info order_info"
          v-if="detailData && (orderStateTxt === '待自提' || orderStateTxt === '已自提')">
          <div class="to_send">
            <div>
              <span>自提地址：</span><span>{{detailData.meetAddress}}</span>
            </div>
          </div>
        </div>

        <div class="order_unique_info order_info"
          v-if="detailData && (orderStateTxt === '待就医' || orderStateTxt === '已就医')">
          <div class="to_send">
            <div>
              <span>预约时间：</span><span>{{detailData.appointTiemStart}}</span>
            </div>
            <div>
              <span>就医地址：</span><span>{{detailData.meetAddress}}</span>
            </div>
            <div>
              <span>备注：</span><span>{{detailData.remarks || '无'}}</span>
            </div>
          </div>
        </div>

        <div class="table_block">
          <el-table
            :data="tableData"
            border
            style="width: 100%">
            <el-table-column
              prop="saleItemList[0].itemName"
              label="商品名称">
            </el-table-column>
            <el-table-column
              prop="saleItemList[0].id"
              label="商品ID">
            </el-table-column>
            <el-table-column
              prop="saleOrderDetailList[0].specName"
              label="规格">
            </el-table-column>
            <el-table-column
              prop="saleOrderDetailList[0].unitPrice"
              label="价格">
            </el-table-column>
            <el-table-column
              prop="saleOrderDetailList[0].quantity"
              label="数量">
            </el-table-column>
            <el-table-column
              label="优惠" >
              <template slot-scope="scope">
                <span>{{scope.row.saleOrderDetailList[0].discount || '无'}}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="金额"
              prop="saleOrderDetailList[0].totalPrice">
            </el-table-column>
            <el-table-column
              label="返回积分"
              prop="backCredit[0]">
            </el-table-column>
          </el-table>
        </div>
        <div class="handle_block">
          <deal-btn
            v-if="detailData"
            :item="detailData" :detailFlag="orderStateTxt" :state="detailData.state" @changeOrderStateTxt="changeOrderStateTxt">
          </deal-btn>
        </div>
      </div>
    </div>

    <!-- 确认就医 or 自提 -->
    <el-dialog
      :title="`确认${doctorOrRecipientTitle}`"
      :visible.sync="doctorOrPickVis"
      :before-close="done => { resetForm('doctorOrPickForm'); done() }">
      <el-form
        :model="doctorOrPickForm" :rules="doctorOrPickFormRules"
        ref="doctorOrPickForm" label-width="100px">
        <el-form-item :label="`${doctorOrRecipientTitle}人`" prop="pickName">
          <el-input
            :disabled="docOrPickOkLoading"
            v-model="doctorOrPickForm.pickName"
            :placeholder="`请输入${doctorOrRecipientTitle}人`"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="pickPhoneNumber">
          <el-input
            :disabled="docOrPickOkLoading"
            v-model="doctorOrPickForm.pickPhoneNumber"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
        <el-form-item :label="`${doctorOrRecipientTitle}时间`" prop="pickTime_mapping">
          <el-date-picker
            :disabled="docOrPickOkLoading"
            v-model="doctorOrPickForm.pickTime_mapping"
            type="datetime"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="() => { doctorOrPickVis = false; resetForm('doctorOrPickForm') }">取 消</el-button>
        <el-button type="primary" @click="confirmDocOrPickOk('doctorOrPickForm')" :loading="docOrPickOkLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
import MainHeader from '@/components/layouts/MainHeader'
import API from '@/config/api.js'
import ErrorConfig from '@/config/error.config.js'
import DealBtn from '@/components/pages/order/DealOrder'

export default {
  name: 'OrderDetail',
  components: { MainHeader, DealBtn },
  beforeRouteEnter (to, from, next) {
    next(vm => vm.initPage())
  },
  data () {
    const validatePhoneNum = (rule, value, callback) => { // 校验手机号
      if (!value) {
        return callback(new Error('请输入手机号'))
      }
      let regNum = /^1[0-9]{10}$/
      if (!regNum.test(value)) {
        return callback(new Error('请输入正确的手机号'))
      }
      callback()
    }
    return {
      crumbsArr: [ // 面包屑
        { name: 'welcome', txt: '首页' }, { name: 'order', txt: '订单管理' }, { txt: '订单详情' }
      ],
      loading: false,
      tableData: [],
      detailData: null,
      orderStateTxt: '',
      doctorOrPickVis: false,
      doctorOrRecipientTitle: '', // 就医或者自提的dialog title
      doctorOrPickFormRules: {
        pickName: [
          { required: true, message: '该项不能为空', trigger: 'blur' }
        ],
        pickPhoneNumber: [
          { required: true, validator: validatePhoneNum, trigger: 'blur' }
        ],
        pickTime_mapping: [
          { required: true, message: '该项不能为空', trigger: 'change' }
        ]
      },
      doctorOrPickForm: {
        orderId: null,
        pickName: '',
        pickPhoneNumber: '',
        pickTime: '',
        pickTime_mapping: ''
      },
      docOrPickOkLoading: false
    }
  },
  computed: {},
  watch: {
    'doctorOrPickForm.pickTime_mapping' (val, oldVal) {
      this.doctorOrPickForm.pickTime = moment(val).format('YYYY-MM-DD HH:mm')
    }
  },
  filters: {},
  methods: {
    initPage () {
      this.loadData()
    },
    async loadData () {
      const { id } = this.$route.params
      this.loading = true // 打开加载框
      const response = await API.getOrderDetail({ id })
      this.loading = false
      const {code, data} = response
      if (code === 1) {
        this.dealDetailData(data)
      } else {
        if (code === -1) {
          const { msg } = response
          this.$message.error(msg)
        } else {
          this.$message.error(ErrorConfig[code])
        }
      }
    },
    dealDetailData (data) {
      this.detailData = data
      this.tableData = []
      this.tableData.push(data)

      let { state } = data
      if (state === 9) { // 待发货
        if (data.saleItemType === 0 && data.logisticsId !== 1) {
          this.orderStateTxt = '待发货'
        }
        if ((data.saleItemType === 0 || data.saleItemType === 2) && data.logisticsId === 1) {
          this.orderStateTxt = '待自提'
        }
        if (data.saleItemType === 1) {
          this.orderStateTxt = '待就医'
        }
      }
      if ('016'.indexOf(state) !== -1) { // 已完成tab的数据
        if (data.saleItemType === 0 && data.logisticsId !== 1) {
          this.orderStateTxt = '已发货'
        }
        if ((data.saleItemType === 0 || data.saleItemType === 2) && data.logisticsId === 1) {
          this.orderStateTxt = '已自提'
        }
        if (data.saleItemType === 1) {
          this.orderStateTxt = '已就医'
        }
      }
    },
    confirmDoctor () { // 确认就医按钮
      this.doctorOrRecipientTitle = '就医'
      this.doctorOrPickForm.orderId = this.detailData.id
      this.doctorOrPickVis = true
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    async confirmDocOrPickOk (formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.docOrPickOkLoading = true
          const response = await API.pickGoods(this.doctorOrPickForm)
          this.docOrPickOkLoading = false
          this.doctorOrPickVis = false
          const { code } = response
          if (code === 1) {
            this.$message({
              message: `${this.doctorOrRecipientTitle}成功`,
              type: 'success'
            })
            this.resetForm('doctorOrPickForm')
            this.loadData()
          } else {
            if (code === -1) {
              const { msg } = response
              this.$message.error(msg)
            } else {
              this.$message.error(ErrorConfig[code])
            }
          }
        } else {
          return false
        }
      })
    },
    changeOrderStateTxt (text) {
      this.orderStateTxt = text
    }
  }
}
</script>

<style scoped lang="scss">
  .main_wrapper {
    padding: 20px 20px 0;
    .main {
      background: #fff;
      padding: 20px;
      .order_status {
        padding: 10px 20px;
        background: #E9CC82;
        font-size: 14px;
        line-height: 14px;
        color: #3B3A42;
      }
      .order_info{
        span {
          font-size: 14px;
          color: #3B3A42;
        }
      }
      .order_baseInfo {
        margin-top: 20px;
        span {
          &:nth-child(even) {
            margin-right: 40px;
          }
        }
      }
      .order_unique_info {
        margin-top: 20px;
        .to_send {
          div {
            margin-top: 20px;
            span {
              &:nth-child(odd) {
                display: inline-block;
                width: 70px;
                text-align: right;
              }
            }
          }
        }
      }
      .table_block {
        margin-top: 40px;
      }
      .handle_block {
        margin-top: 20px;
      }
    }
  }
</style>
